package com.ftp;
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;

import org.apache.commons.net.ftp.FTPClient;  
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;  
import org.apache.log4j.Logger;
  
public class Test {    
	private static Logger logger=Logger.getLogger(Test.class); 
    private static  FTPClient ftp;    
    /** 
     *  
     * @param path 上传到ftp服务器哪个路径下    
     * @param addr 地址 
     * @param port 端口号 
     * @param username 用户名 
     * @param password 密码 
     * @return 
     * @throws Exception 
     */  
    private  boolean connect(String path,String addr,int port,String username,String password) throws Exception {    
        boolean result = false;    
        ftp = new FTPClient();    
        int reply;    
        ftp.connect(addr,port);    
        ftp.login(username,password);    
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);    
        reply = ftp.getReplyCode();    
        if (!FTPReply.isPositiveCompletion(reply)) {    
            ftp.disconnect();    
            return result;    
        }    
        ftp.changeWorkingDirectory(path);    
        result = true;    
        return result;    
    }    
    /** 
     * @  new String(file.getName().getBytes("GBK"), "iso-8859-1")解决乱码
     * @param file 上传的文件或文件夹 
     * @throws Exception 
     */  
    private void upload(File file) throws Exception{    
        if(file.isDirectory()){         
            ftp.makeDirectory(new String(file.getName().getBytes("GBK"), "iso-8859-1"));              
            ftp.changeWorkingDirectory(new String(file.getName().getBytes("GBK"), "iso-8859-1"));    
            String[] files = file.list();           
            for (int i = 0; i < files.length; i++) {    
                File file1 = new File(file.getPath()+"\\"+files[i] );    
                if(file1.isDirectory()){    
                    upload(file1);    
                    ftp.changeToParentDirectory();    
                }else{                  
                    File file2 = new File(file.getPath()+"\\"+files[i]);    
                    FileInputStream input = new FileInputStream(file2);    
                    ftp.storeFile(new String(file2.getName().getBytes("GBK"), "iso-8859-1") ,input);    
                    input.close();                          
                }               
            }    
        }else{    
            File file2 = new File(file.getPath());    
            FileInputStream input = new FileInputStream(file2);    
            ftp.storeFile(new String(file2.getName().getBytes("GBK"), "iso-8859-1"), input);    
            input.close();      
        }    
    } 
    
	public boolean connect(String addr, int port, String username, String password) throws Exception {
		boolean result = false;
		ftp = new FTPClient();
		int reply;
		ftp.connect(addr, port);
		ftp.login(username, password);
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		ftp.enterLocalPassiveMode();
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return result;
		}
		result = true;
		return result;
	}

	public static void putFile(String localPath, String localFileName, String remotePath, String remoteFileName) {
		InputStream inputStream = null;             
         
		File localFile = new File(localPath, localFileName);
		try {
			inputStream = Files.newInputStream(localFile.toPath(), StandardOpenOption.READ);

			if (remotePath != null) {
				/*ftp.makeDirectory(remotePath);
				ftp.changeWorkingDirectory(remotePath);*/
				makeChangeDirectory(remotePath);
			}

			ftp.storeFile(remoteFileName, inputStream);

		} catch (IOException var13) {
			var13.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException var12) {
					var12.printStackTrace();
				}
			}

		}

	}


	
	/**
	 *
	 * 销毁ftp连接
	 *
	 */
	public static void closeFtpConnection() {
		if (ftp != null) {
			if (ftp.isConnected()) {
				try {
					ftp.logout();
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	} 
	public static boolean makeChangeDirectory(String remotePath){
		try {
			
			if(ftp.changeWorkingDirectory(remotePath)){
				return true;
			}							
			String[] arr =  remotePath.split("/");
			for(String aa : arr) {
				System.out.println(aa);
			}
			StringBuffer sbfDir=new StringBuffer();
			int flag = 0;
			//循环生成子目录
			for(String s : arr){
				sbfDir.setLength(0);
				if("/".equals(remotePath.substring(0, 1))){
					if(flag==0) {
						sbfDir.append("/");
					}					
					sbfDir.append(s);
				}else{
					
					sbfDir.append(s);
				}
				flag++;
				System.out.println(sbfDir.toString());
				//尝试切入目录
				if(ftp.changeWorkingDirectory(sbfDir.toString()))
					continue;
				if(!ftp.makeDirectory(s)){
					System.out.println("[失败]ftp创建目录："+sbfDir.toString());
					return false;
				}
				else {
					if(!ftp.changeWorkingDirectory(sbfDir.toString())) {
						System.out.println("切换目录失败");
					}
				}
				System.out.println("[成功]创建ftp目录："+sbfDir.toString());
				
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
   public static void main(String[] args) throws Exception{  
     Test t = new Test();  
    /*  t.connect("/asbank/asxip/user/zdr", "192.168.10.202", 21, "asxip", "pass");  
      File file = new File("C:\\Users\\80430\\tmp\\MEDICL\\20200916\\朝阳银行_职工医疗保险个体到账_211382_20200916.TXT");  
      t.upload(file); 
      System.out.println("ok");*/
     t.connect("192.168.10.202", 21, "asxip", "pass");
     String remoteFileName = "测试.txt";
     
     putFile("E:\\cybank", "测试.txt", "bankfrom/211385/20181231", new String(remoteFileName.getBytes("GBK"), "iso-8859-1"));
     if(t.ftp.changeWorkingDirectory("~")) {
    	 System.out.println("切到根目录");
    	System.out.println(t.ftp.printWorkingDirectory());
     }
     
     closeFtpConnection(); 
   }  
} 